package com.demo.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * 文件流工具  将传入的MultipartFile类型转为File类型，Controller接收到的是MultipartFile类型，EasyExcel.read方法所需要的是File类型。
 */
public class MultipartFileUtil {
//    private final static String STATIC_PATH = "f:/2/";
    private final static String STATIC_PATH = "/Users/yuwenping/Downloads";


    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.getSize() > 0) {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(STATIC_PATH+file.getName());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = Files.newOutputStream(file.toPath());
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
